<template>
  <view class="register-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 主要内容 -->
    <view class="main-content">
      <!-- Logo区域 -->
      <view class="logo-section">
        <image
          class="logo"
          src="/static/VK_MDY_lightmode.png"
          mode="aspectFit"
        />
        <text class="app-name">VKG AI</text>
        <text class="app-slogan">智能文档问答助手</text>
      </view>

      <!-- 注册表单 -->
      <view class="register-form">
        <view class="form-header">
          <text class="form-title">创建账户</text>
          <text class="form-subtitle">请填写以下信息完成注册</text>
        </view>

        <view class="form-group">
          <view class="input-wrapper">
            <text class="input-icon">👤</text>
            <input
              v-model="formData.username"
              class="form-input"
              type="text"
              placeholder="请输入用户名"
              :disabled="loading"
              @blur="validateUsername"
            />
          </view>
          <text v-if="errors.username" class="error-text">{{
            errors.username
          }}</text>
        </view>

        <view class="form-group">
          <view class="input-wrapper">
            <text class="input-icon">📧</text>
            <input
              v-model="formData.email"
              class="form-input"
              type="email"
              placeholder="请输入邮箱地址"
              :disabled="loading"
              @blur="validateEmail"
            />
          </view>
          <text v-if="errors.email" class="error-text">{{ errors.email }}</text>
        </view>

        <view class="form-group">
          <view class="input-wrapper">
            <text class="input-icon">📱</text>
            <input
              v-model="formData.phone"
              class="form-input"
              type="tel"
              placeholder="请输入手机号码"
              :disabled="loading"
              @blur="validatePhone"
            />
          </view>
          <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
        </view>

        <view class="form-group">
          <view class="input-wrapper">
            <text class="input-icon">🔒</text>
            <input
              v-model="formData.password"
              class="form-input"
              type="password"
              placeholder="请输入密码"
              :disabled="loading"
              @blur="validatePassword"
            />
          </view>
          <text v-if="errors.password" class="error-text">{{
            errors.password
          }}</text>
        </view>

        <view class="form-group">
          <view class="input-wrapper">
            <text class="input-icon">🔒</text>
            <input
              v-model="formData.confirmPassword"
              class="form-input"
              type="password"
              placeholder="请确认密码"
              :disabled="loading"
              @blur="validateConfirmPassword"
            />
          </view>
          <text v-if="errors.confirmPassword" class="error-text">{{
            errors.confirmPassword
          }}</text>
        </view>

        <view class="form-options">
          <label class="agree-terms">
            <text class="checkbox-text">我已阅读并同意</text>
            <text class="terms-link" @click="showTerms">《用户协议》</text>
          </label>
        </view>

        <button
          class="register-btn"
          :class="{ 'register-btn-loading': loading }"
          :disabled="loading || !isFormValid"
          @click="handleRegister"
        >
          <text v-if="!loading" class="btn-text">注册</text>
          <view v-else class="loading-spinner">
            <view class="spinner"></view>
            <text class="loading-text">注册中...</text>
          </view>
        </button>

        <view class="login-link">
          <text class="login-text">已有账户？</text>
          <text class="login-btn" @click="goToLogin">立即登录</text>
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <view class="footer">
      <text class="footer-text">© 2024 VKG AI. 保留所有权利</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { authAPI } from "@/api/index";

// 响应式数据
const formData = reactive({
  username: "",
  email: "",
  phone: "",
  password: "",
  confirmPassword: "",
});

const errors = reactive({
  username: "",
  email: "",
  phone: "",
  password: "",
  confirmPassword: "",
});

const agreeTerms = ref(false);
const loading = ref(false);

// 计算属性：表单是否有效
const isFormValid = computed(() => {
  return (
    formData.username.trim() &&
    formData.email.trim() &&
    formData.phone.trim() &&
    formData.password.trim() &&
    formData.confirmPassword.trim() &&
    !errors.username &&
    !errors.email &&
    !errors.phone &&
    !errors.password &&
    !errors.confirmPassword
  );
});

// 生命周期
onMounted(() => {
  // 页面初始化逻辑
});

// 验证用户名
const validateUsername = () => {
  const username = formData.username.trim();
  if (!username) {
    errors.username = "用户名不能为空";
    return false;
  }
  if (username.length < 3) {
    errors.username = "用户名至少3个字符";
    return false;
  }
  if (username.length > 20) {
    errors.username = "用户名不能超过20个字符";
    return false;
  }
  if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(username)) {
    errors.username = "用户名只能包含字母、数字、下划线和中文";
    return false;
  }
  errors.username = "";
  return true;
};

// 验证邮箱
const validateEmail = () => {
  const email = formData.email.trim();
  if (!email) {
    errors.email = "邮箱不能为空";
    return false;
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    errors.email = "请输入有效的邮箱地址";
    return false;
  }
  errors.email = "";
  return true;
};

// 验证手机号
const validatePhone = () => {
  const phone = formData.phone.trim();
  if (!phone) {
    errors.phone = "手机号码不能为空";
    return false;
  }
  const phoneRegex = /^1[3-9]\d{9}$/; // 简单的手机号正则
  if (!phoneRegex.test(phone)) {
    errors.phone = "请输入有效的手机号码";
    return false;
  }
  errors.phone = "";
  return true;
};

// 验证密码
const validatePassword = () => {
  const password = formData.password;
  if (!password) {
    errors.password = "密码不能为空";
    return false;
  }
  if (password.length < 6) {
    errors.password = "密码至少6个字符";
    return false;
  }
  if (password.length > 20) {
    errors.password = "密码不能超过20个字符";
    return false;
  }
  errors.password = "";
  return true;
};

// 验证确认密码
const validateConfirmPassword = () => {
  const confirmPassword = formData.confirmPassword;
  if (!confirmPassword) {
    errors.confirmPassword = "请确认密码";
    return false;
  }
  if (confirmPassword !== formData.password) {
    errors.confirmPassword = "两次输入的密码不一致";
    return false;
  }
  errors.confirmPassword = "";
  return true;
};

// 验证所有字段
const validateAll = () => {
  const usernameValid = validateUsername();
  const emailValid = validateEmail();
  const phoneValid = validatePhone();
  const passwordValid = validatePassword();
  const confirmPasswordValid = validateConfirmPassword();

  return (
    usernameValid &&
    emailValid &&
    phoneValid &&
    passwordValid &&
    confirmPasswordValid
  );
};

// 处理注册
const handleRegister = async () => {
  if (!validateAll()) {
    uni.showToast({
      title: "请检查输入信息",
      icon: "none",
    });
    return;
  }

  try {
    loading.value = true;

    const response = await authAPI.register({
      username: formData.username.trim(),
      email: formData.email.trim(),
      phone: formData.phone.trim(),
      password: formData.password,
    });

    // 考虑到可能的响应格式差异，放宽成功条件
    if (
      response.success ||
      response.code === 200 ||
      response.status === "success" ||
      response.message === "注册成功"
    ) {
      uni.showToast({
        title: "注册成功！",
        icon: "success",
      });

      console.log("注册成功，准备跳转到登录页");
      // 延迟跳转到登录页
      // 立即跳转，不延迟
      console.log("注册成功，立即跳转到登录页");

      // 尝试使用多种跳转方式
      uni.navigateTo({
        url: "/pages/login/index",
        success: () => {
          console.log("navigateTo跳转成功");
          // 跳转成功后显示用户协议
          showTerms();
        },
        fail: (err) => {
          console.error("navigateTo跳转失败:", err);

          // 如果navigateTo失败，尝试使用redirectTo
          uni.redirectTo({
            url: "/pages/login/index",
            success: () => {
              console.log("redirectto跳转成功");
              // 跳转成功后显示用户协议
              showTerms();
            },
            fail: (err2) => {
              console.error("redirectTo跳转失败:", err2);

              // 如果redirectTo也失败，尝试使用reLaunch
              uni.reLaunch({
                url: "/pages/login/index",
                success: () => {
                  console.log("relaunch跳转成功");
                  // 跳转成功后显示用户协议
                  showTerms();
                },
                fail: (err3) => {
                  console.error("reLaunch跳转失败:", err3);
                  uni.showToast({
                    title: "跳转失败，请手动登录",
                    icon: "none",
                  });
                },
              });
            },
          });
        },
      });
    } else {
      uni.showToast({
        title: response.message || "注册失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("注册失败:", error);
    uni.showToast({
      title: error.message || "注册失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 显示用户协议
const showTerms = () => {
  uni.showModal({
    title: "用户协议",
    content:
      "欢迎使用VKG AI！\n\n1. 用户应遵守相关法律法规\n2. 不得上传违法、有害内容\n3. 保护用户隐私，不会泄露个人信息\n4. 服务可能因维护等原因暂时中断\n5. 本协议最终解释权归VKG AI所有",
    showCancel: false,
    confirmText: "我知道了",
  });
};

// 跳转到登录页面
const goToLogin = () => {
  uni.redirectTo({ url: "/pages/login/index" });
};
</script>

<style lang="scss" scoped>
/* 全局样式，去掉滚动条 */
:deep(body) {
  margin: 0;
  padding: 0;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
}

:deep(html) {
  overflow: hidden;
  height: 100vh;
  width: 100vw;
}

:deep(#app) {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

.register-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  width: 100vw;
  margin: 0;
  padding: 0;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200rpx;
  height: 200rpx;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150rpx;
  height: 150rpx;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100rpx;
  height: 100rpx;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  z-index: 1;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.logo-section {
  text-align: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 30rpx;
}

.app-name {
  font-size: 64rpx;
  font-weight: bold;
  color: white;
  display: block;
  margin-bottom: 20rpx;
}

.app-slogan {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.8);
}

.register-form {
  width: 100%;
  max-width: 600rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.form-header {
  text-align: center;
  margin-bottom: 50rpx;
}

.form-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
}

.form-subtitle {
  font-size: 28rpx;
  color: #666;
}

.form-group {
  margin-bottom: 25rpx;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 20rpx;
  padding: 0 30rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;

  &:focus-within {
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
  }
}

.input-icon {
  font-size: 36rpx;
  margin-right: 20rpx;
  color: #999;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
}

.form-input {
  flex: 1;
  height: 100rpx;
  background: transparent;
  border: none;
  outline: none;
  font-size: 32rpx;
  color: #333;

  &::placeholder {
    color: #999;
  }
}

.error-text {
  color: #e74c3c;
  font-size: 24rpx;
  margin-top: 10rpx;
  margin-left: 30rpx;
}

.form-options {
  margin-bottom: 40rpx;
}

.agree-terms {
  display: flex;
  align-items: center;
  cursor: pointer;
  flex-wrap: wrap;
}

.checkbox {
  margin-right: 15rpx;
  transform: scale(0.8);
  display: block;
}

.checkbox-text {
  font-size: 28rpx;
  color: #666;
}

.terms-link {
  font-size: 28rpx;
  color: #667eea;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

.register-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 25rpx;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
  transition: all 0.3s ease;

  &:hover:not(:disabled) {
    transform: translateY(-2rpx);
    box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.register-btn-loading {
  background: #ccc;
}

.btn-text {
  color: white;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.spinner {
  width: 30rpx;
  height: 30rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  border-top: 3rpx solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: white;
  font-size: 28rpx;
}

.login-link {
  text-align: center;
}

.login-text {
  font-size: 28rpx;
  color: #666;
}

.login-btn {
  font-size: 28rpx;
  color: #667eea;
  margin-left: 10rpx;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

.footer {
  padding: 40rpx;
  text-align: center;
  z-index: 1;
}

.footer-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .main-content {
    padding: 20rpx;
  }

  .register-form {
    padding: 40rpx 30rpx;
  }

  .app-name {
    font-size: 56rpx;
  }

  .form-title {
    font-size: 40rpx;
  }
}

/* 小程序和APP端适配 */
/* #ifdef MP-WEIXIN || APP-PLUS */
.register-container {
  padding-top: var(--status-bar-height);
}

.main-content {
  padding-top: calc(40rpx + var(--status-bar-height));
}
/* #endif */

/* H5端适配 */
/* #ifdef H5 */
.register-container {
  height: 100vh;
  overflow: hidden;
}
/* #endif */
</style>
